package com.zhentao.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.zhentao.pojo.User;
import com.zhentao.pojo.Viporder;
import com.zhentao.pojo.Viptaocan;
import com.zhentao.service.UserService;
import com.zhentao.service.ViporderService;
import com.zhentao.service.ViptaocanService;

import com.zhentao.util.PayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/api/alipay")
public class AliPayController {
    @Autowired
    private PayUtil payUtil;
    @Autowired
    private UserService userService;
    @Autowired
    ViporderService viporderService;
    @Autowired
    ViptaocanService viptaocanService;

    private Viporder orderModels = null;
    private String tokens = "";
    
    // 存储订单号与订单ID的映射关系
    private static final Map<String, Integer> orderMapping = new java.util.concurrent.ConcurrentHashMap<>();
//    @Autowired
//    private JwtHelper jwtHelper;

    @PostMapping("/pay")
    public String alipay(@RequestHeader String token, @RequestBody Viporder orderModel) throws AlipayApiException {
        orderModels = orderModel;
        tokens = token;
        
        try {
            // 验证订单是否存在
            Viporder order = viporderService.getById(orderModel.getId());
            if (order == null) {
                return "订单不存在";
            }
            
            // 检查订单状态
            if (order.getStatus() != null && order.getStatus() == 1) {
                return "订单已支付";
            }
            
            // 获取套餐信息
            Viptaocan viptaocan = viptaocanService.getById(order.getViptcid());
            if (viptaocan == null) {
                return "套餐不存在";
            }
            
            // 生成订单号（支付宝的要求）
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String user = UUID.randomUUID().toString().replace("-", "").toUpperCase();
        String OrderNum = time + user;
            
            // 存储订单号与订单ID的映射关系
            orderMapping.put(OrderNum, order.getId());
            
            // 设置订单信息
            order.setUser(userService.getById(order.getUserid()));
            order.setViptaocan(viptaocan);
            
            float orderValue = viptaocan.getPrice().floatValue();
            String subject = viptaocan.getVipname();
            
            System.out.println("商品名字是: " + subject);
            System.out.println("订单金额: " + orderValue);
            System.out.println("订单号: " + OrderNum);
            System.out.println("订单ID: " + order.getId());
            
            // 调用封装好的方法（给支付宝接口发送请求）
            return payUtil.sendRequestToAlipay(OrderNum, orderValue, subject);
            
        } catch (Exception e) {
            System.err.println("支付请求处理异常: " + e.getMessage());
            e.printStackTrace();
            return "支付请求处理失败: " + e.getMessage();
        }
    }

    //    当我们支付完成之后跳转这个请求并携带参数，我们将里面的订单id接收到，通过订单id查询订单信息，信息包括支付是否成功等
    @GetMapping("/toSuccess")
    public String returns(String out_trade_no) throws ParseException {
        try {
            System.out.println("支付回调，订单号: " + out_trade_no);
            
        String query = payUtil.query(out_trade_no);
            System.out.println("支付宝查询结果: " + query);
            
        JSONObject jsonObject = JSONObject.parseObject(query);
        Object o = jsonObject.get("alipay_trade_query_response");
        Map map = (Map) o;
            System.out.println("查询响应: " + map);
            
        Object s = map.get("trade_status");
            if (s != null && s.equals("TRADE_SUCCESS")) {
                // 当支付成功之后要执行的操作
                System.out.println("订单支付成功，开始更新订单状态");
                
                // 根据订单号查找订单（这里需要根据实际情况调整）
                // 由于out_trade_no是支付宝生成的，我们需要通过其他方式找到对应的订单
                // 这里我们假设订单号存储在某个地方，或者通过其他字段关联
                
                // 更新订单状态
                this.updateOrderStatus(out_trade_no);
                
                System.out.println("订单状态更新完成");
                return "redirect:http://localhost:8081/#/paysuccess";
            } else {
                // 支付失败要执行的操作
                System.out.println("订单支付失败，状态: " + s);
                return "redirect:http://localhost:8081/#/payfail";
            }
        } catch (Exception e) {
            System.err.println("支付回调处理异常: " + e.getMessage());
            e.printStackTrace();
            return "redirect:http://localhost:8081/#/payfail";
        }
    }
    
    // 更新订单状态
    private void updateOrderStatus(String outTradeNo) {
        try {
            // 通过订单号映射找到对应的订单ID
            Integer orderId = orderMapping.get(outTradeNo);
            
            if (orderId != null) {
                // 根据订单ID查找订单
                Viporder order = viporderService.getById(orderId);
                
                if (order != null && order.getStatus() == 0) {
                    // 更新订单状态为已支付
                    order.setStatus(1);
                    viporderService.updateById(order);
                    
                    // 更新用户VIP状态
                    updateUserVipStatus(order.getUserid(), order.getViptcid());
                    
                    // 清除映射关系
                    orderMapping.remove(outTradeNo);
                    
                    System.out.println("订单 " + order.getId() + " 状态已更新为已支付");
                } else {
                    System.out.println("订单不存在或已支付: " + orderId);
                }
            } else {
                System.out.println("未找到订单号对应的订单ID: " + outTradeNo);
                // 如果映射中没有找到，尝试通过订单号直接查找
                try {
                    // 这里需要根据实际情况调整，可能需要通过其他字段关联
                    System.out.println("尝试通过其他方式查找订单...");
                } catch (Exception e) {
                    System.err.println("通过其他方式查找订单失败: " + e.getMessage());
                }
            }
            
        } catch (Exception e) {
            System.err.println("更新订单状态异常: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    // 更新用户VIP状态
    private void updateUserVipStatus(Integer userId, Integer viptcid) {
        try {
            User user = userService.getById(userId);
            Viptaocan viptaocan = viptaocanService.getById(viptcid);
            
            if (user != null && viptaocan != null) {
                if (user.getIsVip() == 0) {
                    // 首次成为VIP
                user.setIsVip(1);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date());
                    calendar.add(Calendar.DAY_OF_YEAR, viptaocan.getViptime());
                    user.setVipExpireTime(calendar.getTime());
                } else {
                    // 续费VIP
                    Calendar calendar = Calendar.getInstance();
                    if (user.getVipExpireTime() != null) {
                        calendar.setTime(user.getVipExpireTime());
                    } else {
                        calendar.setTime(new Date());
                    }
                    calendar.add(Calendar.DAY_OF_YEAR, viptaocan.getViptime());
                user.setVipExpireTime(calendar.getTime());
                }
                
                userService.updateById(user);
                System.out.println("用户 " + userId + " VIP状态已更新");
            }
        } catch (Exception e) {
            System.err.println("更新用户VIP状态异常: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // 测试接口
    @GetMapping("/test")
    public Map<String, Object> test() {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "API测试成功");
        result.put("timestamp", new Date());
        return result;
    }

    // 测试支付链接生成
    @GetMapping("/testPaymentUrl")
    public Map<String, Object> testPaymentUrl() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            String testOrderNo = "TEST" + System.currentTimeMillis();
            Float testAmount = 0.01f;
            String testSubject = "测试支付";
            
            String paymentUrl = payUtil.generatePaymentUrl(testOrderNo, testAmount, testSubject);
            
            result.put("code", 200);
            result.put("message", "支付链接生成成功");
            result.put("orderNo", testOrderNo);
            result.put("amount", testAmount);
            result.put("subject", testSubject);
            result.put("paymentUrl", paymentUrl);
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "支付链接生成失败: " + e.getMessage());
            result.put("error", e.getClass().getSimpleName());
            e.printStackTrace();
        }
        
        return result;
    }

    // 测试支付宝配置和签名
    @GetMapping("/testAlipayConfig")
    public Map<String, Object> testAlipayConfig() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 测试支付宝客户端初始化
            AlipayClient testClient = new DefaultAlipayClient(
                "https://openapi-sandbox.dl.alipaydev.com/gateway.do",
                "9021000149677539",
                payUtil.getAppPrivateKey(),
                "JSON",
                "UTF-8",
                payUtil.getAlipayPublicKey(),
                "RSA2"
            );
            
            // 测试生成支付请求
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            request.setReturnUrl("http://y5ace563.natappfree.cc/api/alipay/toSuccess");
            request.setNotifyUrl("http://y5ace563.natappfree.cc/api/alipay/toSuccess");
            
            String bizContent = "{\"out_trade_no\":\"TEST" + System.currentTimeMillis() + "\","
                    + "\"total_amount\":\"0.01\","
                    + "\"subject\":\"测试支付\","
                    + "\"body\":\"VIP会员套餐购买\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}";
            
            System.out.println("测试biz_content: " + bizContent);
            request.setBizContent(bizContent);

            String response = testClient.pageExecute(request).getBody();
            
            result.put("code", 200);
            result.put("message", "支付宝配置测试成功");
            result.put("bizContent", bizContent);
            result.put("response", response);
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "支付宝配置测试失败: " + e.getMessage());
            result.put("error", e.getClass().getSimpleName());
            e.printStackTrace();
        }
        
        return result;
    }


    // 检查支付宝配置
    @GetMapping("/checkConfig")
    public Map<String, Object> checkConfig() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 测试支付宝客户端初始化
            AlipayClient testClient = new DefaultAlipayClient(
                "https://openapi-sandbox.dl.alipaydev.com/gateway.do",
                "9021000149677539",
                payUtil.getAppPrivateKey(),
                "JSON",
                "UTF-8",
                payUtil.getAlipayPublicKey(),
                "RSA2"
            );
            
            result.put("code", 200);
            result.put("message", "支付宝配置检查成功");
            result.put("appId", "9021000149677539");
            result.put("gatewayUrl", "https://openapi-sandbox.dl.alipaydev.com/gateway.do");
            result.put("signType", "RSA2");
            result.put("charset", "UTF-8");
            result.put("format", "JSON");
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "支付宝配置检查失败: " + e.getMessage());
            result.put("error", e.getClass().getSimpleName());
        }
        
        return result;
    }

    // 生成支付二维码
    @PostMapping("/generateQRCode")
    public Map<String, Object> generateQRCode(@RequestHeader String token, @RequestBody Viporder orderModel) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 验证订单是否存在
            Viporder order = viporderService.getById(orderModel.getId());
            if (order == null) {
                result.put("code", 400);
                result.put("message", "订单不存在");
                return result;
            }
            
            // 检查订单状态
            if (order.getStatus() != null && order.getStatus() == 1) {
                result.put("code", 400);
                result.put("message", "订单已支付");
                return result;
            }
            
            // 获取套餐信息
            Viptaocan viptaocan = viptaocanService.getById(order.getViptcid());
            if (viptaocan == null) {
                result.put("code", 400);
                result.put("message", "套餐不存在");
                return result;
            }
            
            // 生成订单号
            String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            String user = UUID.randomUUID().toString().replace("-", "").toUpperCase();
            String OrderNum = time + user;
            
            // 存储订单号与订单ID的映射关系
            orderMapping.put(OrderNum, order.getId());
            
            // 生成支付链接（用于生成二维码）
            String paymentUrl = generatePaymentUrl(OrderNum, viptaocan.getPrice().floatValue(), viptaocan.getVipname());
            
            result.put("code", 200);
            result.put("message", "生成成功");
            result.put("orderNo", OrderNum);
            result.put("amount", viptaocan.getPrice());
            result.put("subject", viptaocan.getVipname());
            result.put("paymentUrl", paymentUrl);
            
            System.out.println("生成的支付链接: " + paymentUrl);
            
        } catch (Exception e) {
            System.err.println("生成二维码异常: " + e.getMessage());
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "生成支付链接失败: " + e.getMessage());
        }
        
        return result;
    }
    
    // 生成支付链接
    private String generatePaymentUrl(String outTradeNo, Float totalAmount, String subject) {
        try {
            // 使用PayUtil生成正确的支付宝支付链接
            return payUtil.generatePaymentUrl(outTradeNo, totalAmount, subject);
                   
        } catch (Exception e) {
            System.err.println("生成支付链接异常: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
    
    // 手动检查支付状态
    @GetMapping("/checkPaymentStatus")
    public Map<String, Object> checkPaymentStatus(@RequestParam String orderNo) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            System.out.println("检查支付状态，订单号: " + orderNo);
            
            // 通过订单号查询支付宝
            String query = payUtil.query(orderNo);
            System.out.println("支付宝查询结果: " + query);
            
            JSONObject jsonObject = JSONObject.parseObject(query);
            Object o = jsonObject.get("alipay_trade_query_response");
            Map map = (Map) o;
            System.out.println("查询响应: " + map);
            
            Object tradeStatus = map.get("trade_status");
            if (tradeStatus != null && tradeStatus.equals("TRADE_SUCCESS")) {
                // 支付成功，更新订单状态
                System.out.println("检测到支付成功，开始更新订单状态");
                this.updateOrderStatus(orderNo);
                
                result.put("code", 200);
                result.put("message", "支付成功");
                result.put("status", "paid");
            } else {
                result.put("code", 200);
                result.put("message", "未支付");
                result.put("status", "unpaid");
            }
            
        } catch (Exception e) {
            System.err.println("检查支付状态异常: " + e.getMessage());
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "检查支付状态失败: " + e.getMessage());
        }
        
        return result;
    }
    
    // 生成简化的支付链接（用于测试）
    private String generateSimplePaymentUrl(String outTradeNo, Float totalAmount, String subject) {
        try {
            // 直接返回支付宝沙箱的测试页面链接
            // 这个链接不需要签名，可以直接用于测试
            String paymentUrl = "https://openapi-sandbox.dl.alipaydev.com/gateway.do?" +
                "app_id=9021000149677539" +
                "&method=alipay.trade.page.pay" +
                "&charset=UTF-8" +
                "&sign_type=RSA2" +
                "&timestamp=" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) +
                "&version=1.0" +
                "&notify_url=" + URLEncoder.encode("http://y5ace563.natappfree.cc/api/alipay/toSuccess", "UTF-8") +
                "&return_url=" + URLEncoder.encode("http://y5ace563.natappfree.cc/api/alipay/toSuccess", "UTF-8") +
                "&biz_content=" + URLEncoder.encode(
                    "{\"out_trade_no\":\"" + outTradeNo + "\"," +
                    "\"total_amount\":\"" + totalAmount + "\"," +
                    "\"subject\":\"" + subject + "\"," +
                    "\"body\":\"VIP会员套餐购买\"," +
                    "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}", 
                    "UTF-8"
                );
            
            System.out.println("生成的简化支付链接: " + paymentUrl);
            
            return paymentUrl;
                   
        } catch (Exception e) {
            System.err.println("生成简化支付链接异常: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
    
    // 从HTML中提取支付链接
    private String extractPaymentUrlFromHtml(String html) {
        try {
            // 查找form action属性
            int actionIndex = html.indexOf("action=\"");
            if (actionIndex != -1) {
                int start = actionIndex + 8; // "action=\"".length()
                int end = html.indexOf("\"", start);
                if (end != -1) {
                    return html.substring(start, end);
                }
            }
            
            // 查找window.location.href
            int hrefIndex = html.indexOf("window.location.href=\"");
            if (hrefIndex != -1) {
                int start = hrefIndex + 22; // "window.location.href=\"".length()
                int end = html.indexOf("\"", start);
                if (end != -1) {
                    return html.substring(start, end);
                }
            }
            
            return null;
        } catch (Exception e) {
            System.err.println("提取支付链接异常: " + e.getMessage());
            return null;
        }
    }

    /*
参数1：订单号
参数2：订单金额
参数3：订单名称
 */

}